/*
 * @Description: 客户订单属性详情页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-14 17:32:43
 */

import React, { useEffect, useMemo, useState } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  Form,
  notification,
  SelectBox,
  Table,
  TextField,
  CheckBox,
  Spin,
  Cascader,
} from 'choerodon-ui/pro';
import { useDataSet } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { ColumnLock, TableButtonType, TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import { Buttons } from 'choerodon-ui/pro/lib/table/Table';
import intl from 'utils/intl';
import { ButtonColor, FuncType } from 'choerodon-ui/pro/lib/button/enum';
import request from 'utils/request';
import { DataSetSelection, FieldType } from 'choerodon-ui/pro/lib/data-set/enum';
import {
  customerOrderAttributeDtlDS,
  returnReasonDS,
} from '../../stores/customerOrderAttributeDtlDS';
import formatterCollections from 'utils/intl/formatterCollections';

import './indexDtl.less';
// import { Cascader } from 'choerodon-ui';

notification.config({
  duration: 3,
  placement: 'bottomRight',
});

interface propstype {
  match: any;
  props: any;
  location: any;
}

const ClassPage: React.FC<propstype> = props => {
  const formDS = useDataSet(() => new DataSet(customerOrderAttributeDtlDS() as DataSetProps));
  const returnReasonListDS = useDataSet(() => new DataSet(returnReasonDS() as DataSetProps));

  const [returnStatus, setReturnStatus] = useState(0); // 是否允许退货

  const { search } = props.location;
  const queryStr: any = new URLSearchParams(search).get('params');
  const urlParamsObj = JSON.parse(decodeURIComponent(queryStr)) || {};

  // 请求详情数据
  useEffect(() => {
    reqOrderTypeOption();
  }, []);

  // 请求默认订单列表，若该组别客户的组别，存在订单类型子值集，则将该子值集的值默认带出，并自动勾选对应的订单类型
  const renderDefaultOrder = () => {
    return request('/hpfm/v1/0/lovs/data', {
      method: 'get',
      query: {
        lovCode: 'DJIOM.P_ORDER_TYPE',
      },
    });
  };

  const reqDtlData = () => {
    const customerOrderConfigId = props.match.params.id;
    if (customerOrderConfigId) {
      formDS.setQueryParameter('groupCode', urlParamsObj.groupCode);
      //   formDS.setQueryParameter('groupCode', urlParamsObj.groupCode);
      //   formDS.setQueryParameter('trulyCode', urlParamsObj.trulyCode);
      formDS.query().then(async res => {
        // 设置列表带过来的参数
        // formDS.current?.set('tradeName', urlParamsObj.tradeName);
        formDS.current?.set('groupName', urlParamsObj.groupName);
        formDS.current?.set('trulyName', urlParamsObj.trulyName);
        // formDS.current?.set('tradeCode', urlParamsObj.tradeCode);
        formDS.current?.set('groupCode', urlParamsObj.groupCode);
        formDS.current?.set('trulyCode', urlParamsObj.trulyCode || 1);
        // 设置默认值
        if (urlParamsObj.edit) {
          // formDS.current?.set('applicableDimensionCode', res.applicableDimensionCode || 'group');
          formDS.current?.set('isIssueNumber', res.isIssueNumber || 0);
          formDS.current?.set('isPoNumber', res.isPoNumber || 0);
          formDS.current?.set('isModelNumber', res.isModelNumber || 0);
          formDS.current?.set('isDjiCustomsClearance', res.isDjiCustomsClearance || 0);
          formDS.current?.set('isSpecialFormat', res.isSpecialFormat || 0);
          formDS.current?.set(
            'destinationCountryCode',
            res.destinationCountryCode || 'INVOICE_ADDRESS'
          );
          formDS.current?.set('isLocalWarehouse', res.isLocalWarehouse || 0);
          formDS.current?.set('isReturn', res.isReturn || 0);
          setReturnStatus(res.isReturn || 0);
        }

        if (res.customerReturnReasonList) {
          res.customerReturnReasonList.forEach(item => {
            // eslint-disable-next-line no-param-reassign
            item.reasonList = [item.orgCode, item.warehouseCode];
          });
          returnReasonListDS.loadData(res.customerReturnReasonList);
        }

        // 若该组别客户的组别，存在订单类型子值集，则将该子值集的值默认带出，并自动勾选对应的订单类型
        if (!res.customerOrderTypeList && urlParamsObj.edit) {
          const defaultOrderList = await renderDefaultOrder();
          console.log(defaultOrderList);
          let orderTypeCode: any = [];
          defaultOrderList.forEach(item => {
            if (item.parentValue === urlParamsObj.groupId) {
              orderTypeCode.push(Number(item.value));
            }
          });
          if (orderTypeCode.length) {
            formDS.current?.set('customerOrderTypeList', orderTypeCode);
          }
        }

        const currentRecord: any = formDS.current;

        // 更新订单类型 全选按钮
        const orderTypeOptionDS = currentRecord.getField('customerOrderTypeList').options;
        updateOrderAllCheckbox(res.customerOrderTypeList || [], orderTypeOptionDS.toData());

        // 更新核销全选按钮
        const verificationOptionDS = currentRecord.getField('customerVerificationItemList').options;
        updateVerificationCheckbox(
          res.customerVerificationItemList || [],
          verificationOptionDS.toData()
        );
      });
    }
  };

  // 请求订单类型option，获取类型数据，方便渲染全选按钮 (不把option放在DS文件的原因是 类型数据刚进来页面时获取不到，渲染不了全选按钮)
  const reqOrderTypeOption = () => {
    request('/hitf/v1/dji-external-interface/get-order-type', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify([]),
    }).then(res => {
      const optionData = res.data || [];
      formDS.addField('customerOrderTypeList', {
        name: 'customerOrderTypeList',
        type: FieldType.object,
        required: true,
        options: orderTypeOptionsDS(optionData),
        textField: 'name',
        valueField: 'id',
        transformResponse: value => {
          const customerOrderTypeList: any = [];
          const data = value || [];
          data.forEach((item: any) => {
            customerOrderTypeList.push(item.orderTypeCode);
          });
          return customerOrderTypeList;
        },
      });
      reqVerificationTypeOption();
    });
  };

  // 订单类型optionsDS
  const orderTypeOptionsDS = optionData => {
    const orderTypeOptionsDataSet = new DataSet({
      selection: 'single' as DataSetSelection,
      autoQuery: false,
      paging: false,
      data: optionData,
    });
    return orderTypeOptionsDataSet;
  };

  // 请求核销类型option，获取类型数据，方便渲染全选按钮 (不把option放在DS文件的原因是 类型数据刚进来页面时获取不到，渲染不了全选按钮)
  const reqVerificationTypeOption = () => {
    request('/hpfm/v1/0/lovs/data', {
      method: 'get',
      query: {
        lovCode: 'DJIOM.VERIFICATION_ITEM',
      },
    }).then(res => {
      const optionData = res || [];
      formDS.addField('customerVerificationItemList', {
        name: 'customerVerificationItemList',
        type: FieldType.object,
        options: verificationTypeOptionsDS(optionData),
        transformResponse: value => {
          const customerVerificationItemList: any = [];
          const data = value || [];
          data.forEach((item: any) => {
            customerVerificationItemList.push(item.verificationItemCode);
          });
          return customerVerificationItemList;
        },
      });
      reqDtlData();
    });
  };

  // 核销类型optionsDS
  const verificationTypeOptionsDS = optionData => {
    const verificationOptionsDataSet = new DataSet({
      selection: 'single' as DataSetSelection,
      autoQuery: false,
      paging: false,
      data: optionData,
    });
    return verificationOptionsDataSet;
  };

  const handleOrderChange = value => {
    const currentRecord: any = formDS.current;
    const optionDS = currentRecord.getField('customerOrderTypeList').options;
    // 判断全选按钮是否全选
    updateOrderAllCheckbox(value || [], optionDS);
  };

  // 更新订单类型 全选按钮
  const updateOrderAllCheckbox = (value, optionData) => {
    if (optionData.length === value.length) {
      formDS.current?.set('orderTypeAll', 'orderTypeAll');
    } else {
      formDS.current?.set('orderTypeAll', '');
    }
  };

  // 更新核销全选按钮
  const updateVerificationCheckbox = (value, optionData) => {
    if (optionData.length === value.length) {
      formDS.current?.set('verificationAll', 'verificationAll');
    } else {
      formDS.current?.set('verificationAll', '');
    }
  };

  const handleVerificationChange = value => {
    const currentRecord: any = formDS.current;
    const optionDS = currentRecord.getField('customerVerificationItemList').options;
    updateVerificationCheckbox(value || [], optionDS);
  };
  // 全选按钮
  const handleSelectAllChange = (value, type) => {
    const checkBoxDS = formDS;
    if (value) {
      checkBoxDS.forEach((record: any) => {
        // 获取option的值 然后塞到Field里面
        const optionDS = record.getField(type).options;
        const saveOptionData: any = [];
        optionDS.forEach(item => {
          // 核销展示项id对应的是value
          const id = item.data.id || item.data.value;
          saveOptionData.push(id);
        });
        record.set(type, saveOptionData);
      });
    } else {
      checkBoxDS.forEach(record => {
        record.set(type, []);
      });
    }
  };

  // 是否允许退货按钮
  const handleReturnChange = value => {
    if (value === 1) {
      returnReasonListDS.reset();
    } else {
      // 是否允许退货 如果是清空退货列表
      returnReasonListDS?.removeAll();
    }
    setReturnStatus(value);
  };

  // function filter(inputValue, path) {
  //   return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
  // }
  // const cascaderOnchange = (value,record) => {
  //   record.set('reasonList', value)
  // }

  // 退货列表列
  const Columns = useMemo<any>(
    () => [
      {
        name: 'returnReasonCode',
        align: 'left',
        editor: urlParamsObj.edit,
        tooltip: TableColumnTooltip.always,
      },
      {
        name: 'reasonList',
        align: 'left',
        editor: () => {
          // const defaultValue = record.get('reasonList');
          // const options: any = returnReasonListDS.getField('reasonList')?.options?.toData();
          return (
            <Cascader
              // showSearch={{ filter }}
              // options={options}
              // value={defaultValue}
              // onChange={(value) => cascaderOnchange(value,record)}
              disabled={!urlParamsObj.edit}
              style={{ width: '100%' }}
            />
          );
        },
      },
      {
        header: intl.get('dji.otc.om.view.field.operationColumn').d('操作'),
        width: 150,
        lock: ColumnLock.right,
        command: ({ record }) => {
          return [
            <Button
              funcType={FuncType.flat}
              key="delete"
              onClick={() => returnReasonListDS.delete(record)}
              disabled={!urlParamsObj.edit}
            >
              {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
            </Button>,
          ];
        },
      },
    ],
    []
  );

  const buttons: Buttons[] = [
    [TableButtonType.add, { disabled: !formDS.current?.get('isReturn') || !urlParamsObj.edit }],
  ];

  // 保存事件
  const handelSave = async () => {
    // 封装订单类型 核销类型 退货原因传参
    const { customerOrderTypeList } = formDS.current?.toData();
    const { customerVerificationItemList } = formDS.current?.toData();
    if (customerOrderTypeList.length === 0) {
      notification.warning({
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提醒'),
        description: intl
          .get(`dji.otc.om.view.reminder.orderTypeEmpty`)
          .d('订单类型不能为空，请检查!'),
      });
      return;
    }

    const OrderTypeList: any = [];
    const VerificationItemList: any = [];

    if (customerOrderTypeList) {
      customerOrderTypeList.forEach(item => {
        OrderTypeList.push({
          orderTypeCode: item,
        });
      });
    }

    if (customerVerificationItemList) {
      customerVerificationItemList.forEach(item => {
        VerificationItemList.push({
          verificationItemCode: item,
        });
      });
    }

    const returnReasonList = returnReasonListDS.toData();
    const customerReturnReasonList: any = [];

    // 校验退货原因是否重复
    const checkObj = {};
    let repeactReasonFlag = false;
    returnReasonList.forEach((item: any) => {
      const key = item.returnReasonCode;
      if (!checkObj[key]) {
        checkObj[key] = key;
      } else {
        repeactReasonFlag = true;
      }
    });

    // 允许退货 且 退货原因重复
    if (returnStatus && repeactReasonFlag) {
      notification.warning({
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提醒'),
        description: intl
          .get(`dji.otc.om.view.reminder.returnReasonRepeated`)
          .d('退货原因重复，请检查!'),
      });
      return;
    }

    if (returnReasonList) {
      returnReasonList.forEach((item: any) => {
        const submitObj = {
          returnReasonCode: item.returnReasonCode,
          orgCode: item.reasonList[0],
          warehouseCode: item.reasonList[1],
        };

        customerReturnReasonList.push(submitObj);
      });
    }

    formDS.current?.set('customerOrderTypeList', OrderTypeList);
    formDS.current?.set('customerVerificationItemList', VerificationItemList);
    formDS.current?.set('customerReturnReasonList', customerReturnReasonList);
    formDS.submit().then(
      res => {
        if (res) {
          reqDtlData();
        }
      },
      () => {
        formDS.reset();
      }
    );
  };

  return (
    <PageHeaderWrapper
      title={intl.get('dji.otc.om.view.menu.customerOrderAttributeDetail').d('客户订单属性详情')}
      header={
        <div>
          <Button
            color={ButtonColor.primary}
            onClick={() => handelSave()}
            disabled={!urlParamsObj.edit}
          >
            {intl.get('dji.otc.om.view.button.save').d('保存')}
          </Button>
        </div>
      }
    >
      <Spin dataSet={formDS}>
        <div className="customer-order-detail">
          <Form
            dataSet={formDS}
            columns={2}
            disabled={!urlParamsObj.edit}
            className="orderTypeStyle"
          >
            {/* <TextField name="tradeName" disabled /> */}
            <TextField name="groupName" disabled />
            <TextField name="trulyName" disabled />
            {/* <SelectBox name="applicableDimensionCode" /> */}
            <SelectBox name="isIssueNumber" />
            <SelectBox name="isPoNumber" labelWidth={200} />
            <SelectBox name="isModelNumber" labelWidth={170} />
            <SelectBox name="isDjiCustomsClearance" />
            <SelectBox name="isSpecialFormat" />
            <SelectBox name="destinationCountryCode" defaultValue="INVOICE_ADDRESS" />
            <SelectBox name="isLocalWarehouse" colSpan={2} />
            {/* <TextField name="local" /> */}
            {/* 订单类型 */}
            <CheckBox
              name="orderTypeAll"
              colSpan={2}
              value="orderTypeAll"
              onChange={value => handleSelectAllChange(value, 'customerOrderTypeList')}
            >
              {intl.get('dji.otc.om.view.field.selectAll').d('全选')}
            </CheckBox>
            {/* <SelectBox name="isLocalWarehouse" colSpan={2} multiple /> */}
            <SelectBox
              name="customerOrderTypeList"
              multiple
              onChange={handleOrderChange}
              colSpan={2}
              labelWidth={170}
              className="SelectBoxStyle"
            />

            {/* 核销展示项 */}
            <CheckBox
              name="verificationAll"
              colSpan={2}
              value="verificationAll"
              labelWidth={170}
              onChange={value => handleSelectAllChange(value, 'customerVerificationItemList')}
            >
              {intl.get('dji.otc.om.view.field.selectAll').d('全选')}
            </CheckBox>
            <SelectBox
              name="customerVerificationItemList"
              multiple
              onChange={handleVerificationChange}
              colSpan={2}
              className="SelectBoxStyle"
            />

            {/* 退货原因 */}
            <SelectBox name="isReturn" colSpan={2} onChange={handleReturnChange} />
          </Form>

          {/* 核销展示项 */}
          {/* <Form
          dataSet={verificationItemListDS}
          columns={2}
          disabled={!urlParamsObj.edit}
          className="verificationStyle"
        >
          <CheckBox
            name="verificationAll"
            colSpan={2}
            value="verificationAll"
            labelWidth={170}
            onChange={value => handleSelectAllChange(value, 'customerVerificationItemList')}
          >
            全选
          </CheckBox>
          <SelectBox
            name="customerVerificationItemList"
            multiple
            onChange={handleVerificationChange}
            colSpan={2}
            className="SelectBoxStyle"
          />
        </Form> */}
          {/* 退货原因 */}
          {/* <Form columns={2} disabled={!urlParamsObj.edit}>
          <SelectBox
            value={returnStatus}
            onChange={handleReturnChange}
            label="是否允许退货"
            labelWidth={170}
            colSpan={2}
          >
            <Option value={1}>是</Option>
            <Option value={0}>否</Option>
          </SelectBox>
        </Form> */}
          <Form dataSet={returnReasonListDS} columns={2} disabled={!urlParamsObj.edit}>
            <SelectBox
              labelWidth={170}
              label={intl.get('dji.otc.om.view.field.reasonListLabel').d('退货原因/库存组织/子库')}
            />
          </Form>
          <Table
            dataSet={returnReasonListDS}
            columns={Columns}
            style={{ marginLeft: 170, marginTop: -35, marginBottom: 15 }}
            buttons={buttons}
          />
        </div>
      </Spin>
    </PageHeaderWrapper>
  );
};

export default formatterCollections({ code: 'dji.otc.om' })(ClassPage);
